package io.renren.modules.webapi.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.FileUtil;
import io.renren.common.utils.R;
import io.renren.modules.file.entity.FileChunkEntity;
import io.renren.modules.file.service.FileService;
import io.renren.modules.file.vo.FileVoEntity;
import io.renren.modules.webapi.entity.InnerFileEntity;
import io.renren.modules.webapi.service.InnerFileService;
import io.renren.modules.webapi.vo.ParamsVoEntity;
import javassist.runtime.Inner;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/webapi/rfile")
public class RfileController {

    @Value("${spring.file.upFinalFolder}")
    private String upFinalFolder;

    @Value("${spring.file.upArchFolder}")
    private String upArchFolder;

    @Autowired
    private FileService fileService;

    @Autowired
    private InnerFileService innerFileService;

    /**
     * 获取文件列表（根据合同）
     * @param params
     * @return
     */
    @RequestMapping("/innerList")
    public R innerList(@RequestParam Map<String, Object> params){
        try {
            InnerFileEntity entity = innerFileService.queryEntity(params);
            List<InnerFileEntity> list = new ArrayList<>();
            if (entity == null) {
                entity = innerFileService.save(params);
            }
            params.put("parentId",entity.getId());
            list = innerFileService.queryList(params);

            return R.ok().put("innerList",list).put("entity",entity);
        } catch (Exception ex) {
            return R.error();
        }
    }

    /**
     * 获取文件列表（根据父类ID）
     * @param params
     * @return
     */
    @RequestMapping("/getRListByPid")
    public R getRListByPid(@RequestParam Map<String, Object> params){
        try {
            List<InnerFileEntity> list = innerFileService.queryList(params);
            return R.ok().put("list",list);
        } catch (Exception ex) {
            return R.error();
        }
    }

    /**
     * 删除项目文件
     * @param fileEntity
     * @return
     */
    @RequestMapping("/deleteRfile")
    public R deleteRfile(@RequestBody InnerFileEntity fileEntity){
        try {
            innerFileService.deleteByID(fileEntity.getId());
            return R.ok();
        } catch (Exception ex) {
            return R.error();
        }
    }


    /**
     * 归档文件
//     * @param fileEntity
     * @return
     */
    @RequestMapping("/saveArch")
    public R saveArch(@RequestBody ParamsVoEntity paramsVoEntity){
        try {
//            innerFileService.deleteByID(fileEntity.getId());
            for (Long id : paramsVoEntity.getIds()) {
                InnerFileEntity fileEntity = innerFileService.selectById(id);
                String path = innerFileService.getParentDir(fileEntity.getId(),"");
                String basePath = paramsVoEntity.getFileName();
                FileUtil.copyFiles(upFinalFolder + path, upArchFolder + basePath + "/" + fileEntity.getFileName());
            }
//
            return R.ok();
        } catch (Exception ex) {
            return R.error();
        }
    }

    /**
     * 获取文件列表（归档文件）
     * @param params
     * @return
     */
    @RequestMapping("/archlist")
    public R list(@RequestParam Map<String, Object> params){
        try {
            String curpath = params.get("curpath").toString();
            File file = new File(upArchFolder + curpath);
            if(!file.exists()) {
                file.mkdirs();
            }
            List<FileVoEntity> fList = fileService.getListByPath(upArchFolder,params);
            return R.ok().put("list",fList);
        } catch (Exception ex) {
            return R.error();
        }
    }

    /**
     * 保存记录文件
     */
    @RequestMapping("/save")
    public R save(@RequestBody InnerFileEntity fileEntity) {
        try {
            innerFileService.save(fileEntity);
//            String path = voEntity.getFilePath();
//            FileUtil.moveFileToTrash(upFinalFolder + path + "/" + voEntity.getFileName());
        }catch (Exception ex) {
            return R.error("创建记录文件失败！");
        }
        return R.ok("创建记录文件成功！");
    }

    /**
     * 删除文件(文件放到回收站)
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody FileVoEntity voEntity) {
        try {
            String path = voEntity.getFilePath();
            FileUtil.moveFileToTrash(upFinalFolder + path + "/" + voEntity.getFileName());
        }catch (Exception ex) {
            return R.error("删除文件出错！");
        }
        return R.ok("删除文件成功！");
    }

    /**
     * 更改档案文件
     */
    @SysLog("更改档案文件")
    @RequestMapping("/update")
    public R update(@RequestBody FileVoEntity voEntity) {
        String path = voEntity.getFilePath();
        String oldName = voEntity.getOldName();
        String newName = voEntity.getNewName();
        File oldFile = new File(upArchFolder + path + "/" + oldName);
        File newFile = new File(upArchFolder + path + "/" + newName);
        if ( oldFile.exists()) {
            if (newFile.exists()) {
                return R.error("文件名重复，请重新命名！");
            }
            oldFile.renameTo(newFile);
            return R.ok();
        } else {
            return R.error("该文件不存在，请刷新重试！");
        }
    }

    /**
     * 删除档案文件(文件放到回收站)
     */
    @RequestMapping("/deleteArch")
    public R deleteArch(@RequestBody FileVoEntity voEntity) {
        try {
            String path = voEntity.getFilePath();
            FileUtil.moveFileToTrash(upArchFolder + path + "/" + voEntity.getFileName());
        }catch (Exception ex) {
            return R.error("删除文件出错！");
        }
        return R.ok("删除文件成功！");
    }

    @PostMapping("/chunkUpload")
//    @RequiresPermissions("file:file:save")
    public void fileChunkUpload(@ModelAttribute FileChunkEntity param, HttpServletRequest request, HttpServletResponse response){
        // response.setStatus对接前端插件
        //        200, 201, 202: 当前块上传成功，不需要重传。
        //        404, 415. 500, 501: 当前块上传失败，会取消整个文件上传。
        //        其他状态码: 出错了，但是会自动重试上传。
        try {
            /**
             * 判断前端Form表单格式是否支持文件上传
             */
            String path = innerFileService.getParentDir(Long.valueOf(param.getRelativePath().toString().split(",")[0]),"");
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(!isMultipart){
                //这里是我向前端发送数据的代码，可理解为 return 数据; 具体的就不贴了
                System.out.println("不支持的表单格式");
                response.setStatus(404);
                response.getOutputStream().write("不支持的表单格式".getBytes());
            }else {
                param.setTaskId(param.getIdentifier());
                innerFileService.chunkUploadByteBuffer(param,upFinalFolder + path);//service层
                response.setStatus(200);
                response.getWriter().print("上传成功");
            }
            response.getWriter().flush();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传文件失败");
            response.setStatus(415);
        }
    }
}
